package org.example.ding.controller;

import org.example.ding.service.CustomUserDetailsService;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.example.ding.service.NutritionService;
import org.example.ding.service.DishService;
import org.example.ding.service.UserService;
import org.example.ding.entity.User;
import org.example.ding.entity.Dish;
import org.example.ding.entity.OrderRecord;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 主页控制器
 */
@Controller
public class HomeController {

    @Autowired
    private NutritionService nutritionService;

    @Autowired
    private DishService dishService;

    @Autowired
    private UserService userService;

    /**
     * 首页
     */
    @GetMapping("/")
    public String home(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                       Model model) {

        try {
            System.out.println("访问首页，用户: " + (principal != null ? principal.getUsername() : "未登录"));

            if (principal != null) {
                model.addAttribute("user", principal);
                System.out.println("用户已登录: " + principal.getUsername());

                // 重定向到用户仪表盘
                return "redirect:/dashboard";
            } else {
                System.out.println("用户未登录，显示访客页面");
                return "index";
            }

        } catch (Exception e) {
            System.err.println("首页加载失败: " + e.getMessage());
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 用户仪表盘页面
     */
    @GetMapping("/dashboard")
    public String dashboard(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                           Model model) {

        if (principal == null) {
            return "redirect:/login";
        }

        try {
            Long userId = principal.getId();

            // 获取用户信息
            model.addAttribute("user", principal);

            // 获取完整的用户对象
            User user = userService.findByUsername(principal.getUsername()).orElse(null);
            if (user == null) {
                System.err.println("用户未找到: " + principal.getUsername());
                model.addAttribute("progress", null);
            } else {
                // 获取今日营养进度
                try {
                    var progress = nutritionService.getTodayNutrition(user);
                    model.addAttribute("progress", progress);
                    System.out.println("营养进度获取成功: " + progress);
                } catch (Exception e) {
                    System.err.println("获取营养进度失败: " + e.getMessage());
                    e.printStackTrace();
                    model.addAttribute("progress", null);
                }
            }

            // 获取推荐菜品（使用热门菜品作为推荐）
            try {
                List<Dish> recommendations = dishService.getPopularDishes(15);
                model.addAttribute("breakfastRecommendations", recommendations.subList(0, Math.min(5, recommendations.size())));
                model.addAttribute("lunchRecommendations", recommendations.subList(0, Math.min(5, recommendations.size())));
                model.addAttribute("dinnerRecommendations", recommendations.subList(0, Math.min(5, recommendations.size())));
            } catch (Exception e) {
                System.err.println("获取推荐菜品失败: " + e.getMessage());
                model.addAttribute("breakfastRecommendations", List.of());
                model.addAttribute("lunchRecommendations", List.of());
                model.addAttribute("dinnerRecommendations", List.of());
            }

            // 获取所有菜品（用于完整菜单）
            try {
                List<Dish> allDishes = dishService.getAllAvailableDishes();
                model.addAttribute("allDishes", allDishes);
            } catch (Exception e) {
                System.err.println("获取所有菜品失败: " + e.getMessage());
                model.addAttribute("allDishes", List.of());
            }

            return "dashboard";

        } catch (Exception e) {
            System.err.println("仪表盘加载失败: " + e.getMessage());
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 关于页面
     */
    @GetMapping("/about")
    public String about() {
        return "about";
    }

    /**
     * 联系我们页面
     */
    @GetMapping("/contact")
    public String contact() {
        return "contact";
    }

    /**
     * 帮助页面
     */
    @GetMapping("/help")
    public String help() {
        return "help";
    }

    /**
     * 隐私政策页面
     */
    @GetMapping("/privacy")
    public String privacy() {
        return "privacy";
    }

    /**
     * 服务条款页面
     */
    @GetMapping("/terms")
    public String terms() {
        return "terms";
    }
}
